package com.dlc.yunguang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dlc.commonlibrary.dialog.ActionSheetDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.compress.CompressHelper;
import com.dlc.commonlibrary.utils.glide.transform.CircleTransform;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.base.BaseApplication;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.net.bean.LoginBean;
import com.dlc.yunguang.net.protocol.UserProto;
import com.dlc.yunguang.R;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.dlc.yunguang.R.id.iv_head;

/**
 * Created by Administrator on 2017/7/18 0018.
 */

public class SettingActivity extends BaseActivity {

    private static final int REQUEST_NICKNAME = 2333;
    public final static int IMAGE_PICKER = 1000;
    public final static int TAKE_PHONE = 1001;

    @BindView(R.id.titleBar)
    TitleBar mTitleBar;
    @BindView(iv_head)
    ImageView mIvHead;
    @BindView(R.id.item_avatar)
    CommonItemView mItemAvatar;
    @BindView(R.id.item_nickname)
    CommonItemView mItemNickname;

    @BindView(R.id.btn_exit)
    Button btnExit;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_setting;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTitleBar.leftExit(this);
        initView();
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                BaseApplication.moveActivity(new LoginActivity());
                BaseApplication.exitApp();
                startActivity(new Intent(SettingActivity.this, LoginActivity.class));
            }
        });
    }

    private void initView() {
        loadAvatar(UserHelper.get().getAvatar());
        mItemNickname.setContent(UserHelper.get().getNickname());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_NICKNAME:
                    mItemNickname.setContent(UserHelper.get().getNickname());
                    setResult(RESULT_OK);
                    break;
            }
        }

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            switch (requestCode) {
                case IMAGE_PICKER:
                case TAKE_PHONE:

                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(
                            ImagePicker.EXTRA_RESULT_ITEMS);
                    if (images.size() > 0) {
                        String path = images.get(0).path;
                        loadAvatar(path);
                        processAndUpload(path);
                    } else {
                        Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }
    }

    private void processAndUpload(String path) {

        LogPlus.e("" + path);

        showWaitingDialog("正在上传", true);
        Observable.just(path).subscribeOn(Schedulers.io()).map(new Func1<String, File>() {
            @Override
            public File call(String s) {
                File newFile = CompressHelper.getDefault(getActivity()).compressToFile(new File(s));
                return newFile;
            }
        }).flatMap(new Func1<File, Observable<LoginBean>>() {
            @Override
            public Observable<LoginBean> call(File file) {
                return UserProto.get().alterHead(file);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<LoginBean>() {
            @Override
            public void onCompleted() {
                dismissWaitingDialog();
                showToast("上传成功");
            }

            @Override
            public void onError(Throwable e) {
                LogPlus.e("上传失败", e);
                dismissWaitingDialog();
                showToast(e.getMessage());
            }

            @Override
            public void onNext(LoginBean loginBean) {
                UserHelper.get().saveAvatar(loginBean.data.avatar);
                setResult(RESULT_OK);
            }
        });
    }

    @OnClick({R.id.item_avatar, R.id.item_nickname})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.item_avatar:
                showActionDialog();
                break;
            case R.id.item_nickname:
                Intent intent = new Intent(getActivity(), ChangeNicknameActivity.class);
                startActivityForResult(intent, REQUEST_NICKNAME);
                break;
        }
    }

    /**
     * 加载头像
     *
     * @param path
     */
    private void loadAvatar(String path) {
        Glide.with(this)
                .load(path)
                .placeholder(R.mipmap.ic_default_avatar)
                .dontAnimate()
                .transform(new CircleTransform(getActivity()))
                .into(mIvHead);
    }

    private void showActionDialog() {

        ActionSheetDialog sheetDialog = ActionSheetDialog.newBuilder(getActivity())
                .addItem("照相")
                .addItem("从相册选择")
                .setOnSheetItemClickListener(new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        switch (which) {
                            case 0:
                                Toast.makeText(SettingActivity.this, "照相", Toast.LENGTH_SHORT).show();
                                Intent intent =
                                        new Intent(SettingActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,
                                        true); // 是否是直接打开相机
                                startActivityForResult(intent, TAKE_PHONE);
                                break;
                            case 1:
                                Toast.makeText(SettingActivity.this, "从相册选择", Toast.LENGTH_SHORT)
                                        .show();
                                Intent intent1 =
                                        new Intent(SettingActivity.this, ImageGridActivity.class);
                                startActivityForResult(intent1, IMAGE_PICKER);
                                break;
                        }
                    }
                })
                .build();

        sheetDialog.show();
    }
}
